package cn.com.cifi.mars.web.action.sync;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import cn.com.cifi.mars.common.base.BaseAction;
import cn.com.cifi.mars.common.bean.R;
import cn.com.cifi.mars.service.IdmPositionGroupService;
import cn.com.cifi.mars.service.IdmPositionService;
import cn.com.cifi.mars.service.IdmUserService;
import cn.com.cifi.mars.service.OrgService;
import cn.com.cifi.mars.service.SysProjectFetchNumberService;
import cn.com.cifi.mars.util.StrUtils;

@RestController
public class IdmSyncController extends BaseAction implements IIdmSyncController {
	@Autowired
	private IdmUserService idmUserService;
	@Autowired
	private IdmPositionService idmPositionService;
	@Autowired
	private IdmPositionGroupService idmPositionGroupService;
	@Autowired
	private OrgService orgService;
	@Autowired
	private SysProjectFetchNumberService sysProjectFetchNumberService;
	/**
	 * 增量同步用户接口信息
	 */
	@Override
	public R syncUser(String apiVersion, String time, String alias) {
		return ok(idmUserService.syncUser(time, "0", alias));
	}

	/**
	 * 增量同步岗位
	 */
	@Override
	public R syncPosition(String apiVersion, String time,String jobNum) {
		List<String> jobNums = idmPositionService.getJobNumList();
		return ok(idmPositionService.syncPosition(time, "0",jobNum,jobNums));
	}

	/**
	 * 增量同步岗位组
	 */
	@Override
	public R syncPositionGroup(String apiVersion, String time,String jobGroupNum) {
		List<String> groupIds = idmPositionGroupService.getJobDefinitionsIdList();
		return ok(idmPositionGroupService.syncPositionGroup(time, "0",jobGroupNum,groupIds));
	}
	
    /**
	 * 增量拉取组织机构
	 */
    @Override
	public R incrementSyncIdmOrg(String apiVersion, String timestamp, String orgdepid) {
    	if(StrUtils.isEmpty(timestamp)) {
    		timestamp = StrUtils.getTimeStamp2(25);
    	}
    	List<String> orgdepids = orgService.getOrgdepidList();
    	List<String> projectIds = orgService.incrementSyncIdmOrg(orgdepid,timestamp,"0",orgdepids,new ArrayList<>());
    	//清洗组织树
    	orgService.addByStagesV2();
    	//项目取数
        if(CollectionUtils.isNotEmpty(projectIds)) {
       	 for(String projectId : projectIds) {
				sysProjectFetchNumberService.syncProjectFetchNumber(projectId,null);
			}
        }
		return ok(projectIds);
	}


	/**
	 * 初始化项目取数表
	 */
	@Override
	public R initProjectFetchNumber(String apiVersion,String projectId) {
		return ok(sysProjectFetchNumberService.init(projectId));
	}

	/**
	 * 初始化项目树
	 */
	@Override
	public R initProjectTree(String apiVersion) {
		return ok(orgService.addByStagesV2());
	}
}
